package server;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleServer {
	static List<Player> players = new ArrayList<Player>();
	static List<Game> games = new ArrayList<Game>();
	private final static char EOF = (char) 0x00;
	
	public static void main(String args[]) {
		// create a serverSocket connection on port 9999
		ServerSocket s = null;
		try {
			s = new ServerSocket(9999);

			System.out.println("Server started. Waiting for connections...");
			// wait for incoming connections
			while (true) {
				Socket incoming = s.accept();
				Player p = new Player(incoming);
				players.add(p);
				Thread playerThread = new Thread(p, "Player" + players.size());
				playerThread.start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (s != null)
					s.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static List<Player> ListPlayers(Game game) {
		List<Player> playersInGame = new ArrayList<Player>();
		for (Player p:players) {
			if (p.getGame() == game){
				playersInGame.add(p);
			}
		}
		return playersInGame;
	}
	public static void SendMessage(Game game,Player player,String message) {
		for(Player p: SimpleServer.players){
			//TODO only send to players in same game
			p.getData_out().print("<chat FROM='" + player.toString() +"' MESSAGE='" + message.trim() + "' />" + EOF);
			p.getData_out().flush();
		}
		System.out.println(player.toString()+" Said to ALL: " + message.trim());
	}
	public static Game CreateGame(Player host,int maxPlayers,int board, int time, boolean keryo, boolean tour) {
		Game g = new Game(host,maxPlayers, board, time,keryo, tour);
		games.add(g);
		return g;
	}
	public static void SendGameList(Player player) {
		//TODO send a real game list
		player.data_out.print("<games><game maxplayers='2' size='19' keryo='false' time='300' tour='true' /><game maxplayers='5' size='19' keryo='false' time='300' tour='false' /><game maxplayers='2' size='13' keryo='true' time='300' tour='true' /></games>");
		player.data_out.flush();
	}
}